package com.jeecms.wicool.dao.lottery.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.common.hibernate3.Finder;
import com.jeecms.common.hibernate3.HibernateBaseDao;
import com.jeecms.common.page.Pagination;
import com.jeecms.wicool.dao.lottery.ActiveConfigDao;
import com.jeecms.wicool.entity.lottery.ActiveConfig;

@Repository
public class ActiveConfigDaoImpl extends
		HibernateBaseDao<ActiveConfig, Integer> implements ActiveConfigDao {
	
	@Override
	protected Class<ActiveConfig> getEntityClass() {
		// TODO Auto-generated method stub
		return ActiveConfig.class;
	}
	public Pagination getPage(String name,Integer status,String startTime,String endTime, int pageNo, int pageSize,CmsUser user) {
		Finder f = Finder.create("from ActiveConfig bean where 1=1");
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (!StringUtils.isBlank(name)){
			f.append(" and bean.name like :userName");
			f.setParam("name",  "%"+name+"%" );
		}if (status!=null){
			f.append(" and bean.status = :status");
			f.setParam("status",status);
		}if (!StringUtils.isBlank(startTime)){
			startTime=startTime+" 00:00:00";
			try {
				Date start=simpleTime.parse(startTime);
			
			f.append(" and bean.startTime >= :start");
			f.setParam("start",  start );
			
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}if (!StringUtils.isBlank(endTime)){
			endTime=endTime+" 23:59:59";
			try {
				Date end = simpleTime.parse(endTime);
			
			f.append(" and bean.endTime <= :end");
			f.setParam("end",  end );
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}if(user.getShopId()!=null){
			f.append(" and bean.shop.id = :shopId");
			f.setParam("shopId",user.getShopId());
		}
		f.append(" order by bean.id desc");
		return find(f, pageNo, pageSize);
	}
	
	@Override
	public ActiveConfig findById(Integer id) {
		ActiveConfig entity = get(id);
		return entity;
	}
	@Override
	public ActiveConfig save(ActiveConfig bean) {
		getSession().save(bean);
		return bean;
	}
	@Override
	public ActiveConfig deleteById(Integer id) {
		ActiveConfig entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	@Override
	public List<ActiveConfig> getAll(CmsUser user) {
		Finder f= Finder.create("select bean from ActiveConfig bean where 1=1 ");
		if(user.getShopId()!=null){
			f.append(" and bean.shop.id = :shopId");
			f.setParam("shopId",user.getShopId());
		}
		f.append(" order by bean.id desc");
		return find(f);
	}
}